package com.easy.test.task;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.easy.handler.Handler;
import com.easy.test.util.FileData;


public class SendDataHandler implements Handler{
	private Logger logger = LoggerFactory.getLogger(getClass());
	private List<Map<String, Object>> taskList;
	private CountDownLatch cdl;
	public SendDataHandler(CountDownLatch cdl) {
		this.cdl = cdl;
	}
	@Override
	public boolean doBizBefore() {
		//checkData
		return true;
	}

	@Override
	public boolean processInThread() {
		long startTime = System.currentTimeMillis();
	 	try{
			/*for(Map<String, Object> map : taskList){
				long id = Long.valueOf(map.get("id").toString());
				Map<String, FileData> fileParams= ClientProxy.get(ILgtNbExpAction.class).getGoodsImageFileParamsByID(id);
				doSendData(map, fileParams);
			}*/
	    }catch (Exception localException){
	    	logger.error("SendGoodsRecordHandler-processInThread", localException);
		}finally{
	    	cdl.countDown();
	    	long endTime = System.currentTimeMillis();
	    	System.out.println("=============="+cdl.getCount()  +" +++++++++++++"+((endTime-startTime)));
		}
		return true;
	}

	@Override
	public boolean doBizAfter() {
		taskList=null;
		//统计+监控
		return true;
	}

	public List<Map<String, Object>> getTaskList() {
		return taskList;
	}

	public void setTaskList(List<Map<String, Object>> taskList) {
		this.taskList = taskList;
	}
	
	private void doSendData(Map<String, Object> textData,Map<String, FileData> fileParams){
		//xml模板
		long id = Long.valueOf(textData.get("id").toString());
		String msg = getXmlTemplate();
		for(Map.Entry<String, Object> entry :  textData.entrySet()){
			String key = entry.getKey();
			String value = entry.getValue()==null ? "" : entry.getValue().toString();
			msg = msg.replace("#"+key, value);
		}
		System.out.println("===========xmlData:"+msg);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date dt = new Date();
		// 请填写"服务申请"中的账号和密钥
		String userId = "";
		String secret = "";
		String url = "";
		//String secKey = "4BAEwggEf";
		/*userId=PropertiesUtils.getPropertiesValue("lgtnb.username")==null 
				? userId :PropertiesUtils.getPropertiesValue("lgtnb.username");
		secret=PropertiesUtils.getPropertiesValue("lgtnb.pwd")==null 
				? secret :PropertiesUtils.getPropertiesValue("lgtnb.pwd");
		url= PropertiesUtils.getPropertiesValue("lgtnb.serviceUrl")==null 
				? url :PropertiesUtils.getPropertiesValue("lgtnb.serviceUrl");
		//secKey= PropertiesUtils.getPropertiesValue("lgtnb.secKey")==null 
		//		? secKey :PropertiesUtils.getPropertiesValue("lgtnb.secKey");
		*/
		
		try {
			/*Map<String, String> map = new HashMap<String, String>();
			map.put("userid", userId);
			map.put("timestamp", sdf.format(dt));
			map.put("sign", MD5.encode(userId + secret + sdf.format(dt)));
			map.put("xmlstr", msg);
			map.put("msgtype", "cnec_jh_hscode");
			map.put("customs", "3109");
			
			HttpConnector httpConnector = new HttpConnector();
			String result = httpConnector.doPostFile(url, map, fileParams, 60000, 60000);
			doHandlerResult(result,id);*/
			System.out.println("******请求报文Start******");
			System.out.println(msg);
			System.out.println("******请求报文End********");
			System.out.println("******响应报文Start******");
			//System.out.println(result);
			System.out.println("******响应报文End******");
		/*}catch (DocumentException e) {
			// TODO Auto-generated catch block
			logger.error("解析响应信息出错", e);*/
		}catch (Exception e) {
			logger.error("发送数据出错", e);
		}
	}
	private void doHandlerResult(String xmlResult,long id) throws DocumentException{
		Document doc = null;
		doc = DocumentHelper.parseText(xmlResult); // 将字符串转为XML
		Element rootElt = doc.getRootElement(); // 获取根节点
		Element header = rootElt.element("Header"); ///获取根节点下的子节点Header
		// 遍历header节点
	    String result 	= header.elementTextTrim("Result"); //T：操作成功；F：操作失败
	    String resultMsg = header.elementTextTrim("ResultMsg");//结果描述（操作失败时必需）
	    String productId = header.elementTextTrim("ProductId");//系统自动生成货号
	    Map<String,Object> params = new HashMap<String,Object>();
	    params.put("result", result);
	    params.put("resultMsg", resultMsg);
	    params.put("productId", productId);
	    //ClientProxy.get(ILgtNbExpAction.class).updateNbgGoodsRecordByid(id, params);
	    
	}
	private String  getXmlTemplate(){
		String msg = "";
		msg = msg + "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>";
		msg = msg + "<Message>";
		msg = msg + "<Header>";
		msg = msg + "<CustomsCode>#customscode</CustomsCode>"; 
		msg = msg + "<OrgName>#orgname</OrgName>";       
		msg = msg + "</Header>";
		msg = msg + "<Body>";
		msg = msg + "<Name>#name</Name>";
		msg = msg + "<NameEn>#nameen</NameEn>";
		msg = msg + "<HsCode>#hsode</HsCode>";
		msg = msg + "<HsNumber>#hsnumber</HsNumber>";
		msg = msg + "<Weight>#weight</Weight>";
		msg = msg + "<Property>#property</Property>";
		msg = msg + "<Gproduction>#gproduction</Gproduction>";
		msg = msg + "<Brand>#brand</Brand>";
		msg = msg + "<Unit>#unit</Unit>";
		msg = msg + "<Guse>#guse</Guse>";
		msg = msg + "<Gcomposition>#gcomposition</Gcomposition>";
		msg = msg + "<Gfunction>#gfunction</Gfunction>";
		msg = msg + "<Detail>#detail</Detail>";
		msg = msg + "<DsSku>#dssku</DsSku>";
		msg = msg + "<DsSkuCode>#dsskucode</DsSkuCode>";
		msg = msg + "<Comments>#comments</Comments>";
		msg = msg + "<WarehouseCode>#warehousecode</WarehouseCode>";
		msg = msg + "<BizType>#biztype</BizType>";
		msg = msg + "<Flag>#flag</Flag>";
		msg = msg + "<Supplier>#supplier</Supplier>";
		msg = msg + "<HsfileName>#hsfilename</HsfileName>";
		msg = msg + "<CpfileName>#cpfilename</CpfileName>";
		msg = msg + "</Body>";
		msg = msg + "</Message>";
		return msg;
	}

}
